<template>
    <div>
      <h1>WebRTC File Transfer</h1>
      <input type="file" ref="fileInput" />
      <button @click="sendFile">Send File</button>
    </div>
  </template>
  
  <script>
  import { ref, onMounted } from 'vue';

  // 实例化rtc连接对象
  const pc = new RTCPeerConnection()

  // 处理接收的offer
  const offerHandler = async (offer) =>{
    // 设置远程描述
    await pc.setRemoteDescription(new RTCSessionDescription(offer))
    // 生成对应的回复
    const answer = await pc.createAnswer()
    await pc.setLocalDescription(answer)
    // 通过信令服务器发送生成的answer

  }

  const dataChannelHandler = async ()=>{

  }

  // 处理接收到的answer
  const answerHandler = async (answer) =>{
    pc.setRemoteDescription(new RTCSessionDescription(answer))
  }

  // 处理候选人
  const candidateHandler = async (candidate)=>{
    await pc.addIceCandidate(candidate)
  }
  
  export default {
    setup() {
      const peerConnection = new RTCPeerConnection({
        iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
      });
      const socket = new WebSocket('ws://localhost:8080');
      const dataChannel = ref(null);
      const fileInput = ref(null);
  
      // WebSocket 事件处理
      socket.onmessage = async (event) => {
        console.log("aaa:",event.data)
        const message = JSON.parse(event.data);
  
        if (message.type === 'offer') {
          await peerConnection.setRemoteDescription(new RTCSessionDescription(message));
          const answer = await peerConnection.createAnswer();
          await peerConnection.setLocalDescription(answer);
          socket.send(JSON.stringify({ type: 'answer', sdp: answer.sdp }));
        } else if (message.type === 'answer') {
          await peerConnection.setRemoteDescription(new RTCSessionDescription(message));
        } else if (message.candidate) {
          try {
            await peerConnection.addIceCandidate(message.candidate);
          } catch (e) {
            console.error('Error adding received ICE candidate', e);
          }
        }
      };
  
      peerConnection.onicecandidate = (event) => {
        if (event.candidate) {
          socket.send(JSON.stringify({ candidate: event.candidate }));
        }
      };
  
      peerConnection.ondatachannel = (event) => {
        dataChannel.value = event.channel;
        dataChannel.value.onmessage = (e) => {
          console.log('Received data:', e.data);
        };
      };
  
      const startConnection = () => {
        dataChannel.value = peerConnection.createDataChannel('fileChannel');
        dataChannel.value.onopen = () => console.log('Data channel opened');
        dataChannel.value.onmessage = (e) => {
          console.log('Received data:', e.data);
        };
      };
  
      const createOffer = async () => {
        const offer = await peerConnection.createOffer();
        await peerConnection.setLocalDescription(offer);
        socket.send(JSON.stringify({ type: 'offer', sdp: offer.sdp }));
      };
  
      const sendFile = () => {
        const file = fileInput.value.files[0];
        if (dataChannel.value && file) {
          dataChannel.value.send(file);
          console.log('File sent:', file.name);
        }
      };
  
      onMounted(() => {
        startConnection();  // 自动调用开始连接
        createOffer();      // 自动生成并发送 Offer
      });
  
      return { sendFile, fileInput };
    },
  };
  </script>
  
  <style>
  button {
    margin: 5px;
  }
  </style>
  